package com.ruoyi.core.config.wx;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.core.config.utils.WxUtil;
import com.ruoyi.core.config.vo.LoginVo;
import com.ruoyi.core.domain.bo.UserBo;
import com.ruoyi.core.domain.vo.UserVo;
import com.ruoyi.core.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 小程序登录鉴权
 */
@RequestMapping("core/wx")
@RestController
@RequiredArgsConstructor
@Slf4j
@Validated
public class WxPhoneLoginController extends BaseController {

    private static final String PHONE_PATTERN = "^1[3-9]\\d{9}$"; // 手机号正则表达式
    private final IUserService userService;

    /**
     * @return
     */

    private static boolean validate(String phoneNum) {
        Pattern pattern = Pattern.compile(PHONE_PATTERN);
        Matcher matcher = pattern.matcher(phoneNum);
        return matcher.matches();
    }

    /**
     * @param mobile
     * @return
     */
    @SaIgnore
    @GetMapping("/loginByMobile")
    public R<LoginVo> login(@NotBlank(message = "手机号不能为空") String mobile) {
        if(!validate(mobile)){
            return R.fail("手机号格式错误");
        }
        //通过缓存 判断用户
        UserVo userVo = WxUtil.getUserVoByToken();
        if (ObjectUtil.isNotNull(userVo)) {
            //刷新缓存，
            userService.updateByBo(BeanUtil.toBean(userVo,UserBo.class));
            WxUtil.refreshWxUser(userVo, false);
            return R.ok("登录成功", new LoginVo(StpUtil.getTokenValue(), userVo, "0"));
        }
        //根据openid查询数据库是否有该用户，
        userVo = userService.getByTel(mobile);
        if (ObjectUtil.isNull(userVo)) {
            //无用户信息保存到数据库
            userVo = userService.setWxUserByTel(mobile);
            //登录缓存
            WxUtil.refreshWxUser(userVo, true);
            return R.ok("登录成功", new LoginVo(StpUtil.getTokenValue(), userVo, "1"));
        }
        //有用户信息直接登录
        // 更新数据库存信息
        userVo.setLastLoginTime(new Date());
        userService.updateByBo(BeanUtil.toBean(userVo,UserBo.class));
        WxUtil.refreshWxUser(userVo, true);

        return R.ok("登录成功", new LoginVo(StpUtil.getTokenValue(), userVo, "0"));

    }

}
